package com.skp.shaphan.ui.fxconnectioncontrols;

import java.lang.reflect.Field;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Properties;

import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ComboBox;
import javafx.scene.control.TextField;

public class ConnectionController {
	private Properties properties;
	protected HashMap<String, SimpleStringProperty> values;

	public void setProperties(Properties properties) {
		this.properties = properties;
	}
	
	public Properties getProperties() {
		// The binding doesn't automatically update the properties
		// in the properties object, so we have to do that manually
		if(values != null) {
			Enumeration<Object> keys = this.properties.keys();
			while(keys.hasMoreElements()) {
				Object key = keys.nextElement();
				if(key != null && values.get(key) != null) {
					this.properties.put(key, values.get(key).getValue());
				}
			}
		}
		return this.properties;
	}
	
	public void init() {
		values = new HashMap<String, SimpleStringProperty>();
		
		for(Field field : this.getClass().getDeclaredFields()) {
			if(properties.containsKey(field.getName())) {
				Object fieldValue = null;
				try {
					fieldValue = field.get(this);
				} catch (IllegalArgumentException e) {
					e.printStackTrace();
				} catch (IllegalAccessException e) {
					e.printStackTrace();
				}
				if(fieldValue == null) {
					System.err.println("field " + field.getName() + " not set");
				} else if(fieldValue instanceof TextField) {
					TextField textField = (TextField) fieldValue;
					SimpleStringProperty value = new SimpleStringProperty((String)properties.get(field.getName()));
					values.put(field.getName(), value);
					textField.textProperty().bindBidirectional(value);
				} else if(fieldValue instanceof ComboBox) {
					@SuppressWarnings("unchecked")
					ComboBox<String> comboField = (ComboBox<String>) fieldValue;
					SimpleStringProperty value = new SimpleStringProperty((String)properties.get(field.getName()));
					comboField.valueProperty().bindBidirectional(value);
				} else if(fieldValue instanceof CheckBox) {
					CheckBox checkBoxField = (CheckBox) fieldValue;
					SimpleBooleanProperty value = new SimpleBooleanProperty(properties.get(field.getName()).toString().equalsIgnoreCase("yes"));
					checkBoxField.selectedProperty().bindBidirectional(value);
				} else {
					System.err.println("Unknown control type: " + fieldValue.getClass().getName() + "; can't bind");
				}
			} else {
				System.out.println("No property found for: " + field.getName());
			}
		}
	}
}
